package com.haochang.chunkvod.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONObject;

import com.haochang.base.BaseApplication;
import com.haochang.chunkvod.app.common.user.UserToken;
import com.haochang.chunkvod.app.config.ApiConfig;
import com.haochang.chunkvod.app.utils.ActivityTaskUtil;
import com.haochang.chunkvod.app.utils.CollectionUtils;
import com.haochang.chunkvod.app.utils.KeyguardManagerUtil;
import com.haochang.chunkvod.app.utils.VibratorUtil;
import com.haochang.chunkvod.controller.activity.order.OrderHomePageActivity;
import com.haochang.chunkvod.model.order.RoomInfo;
import com.haochang.chunkvod.tools.thirdparty.network.http.httpenum.HttpCacheEnum;
import com.haochang.chunkvod.tools.thirdparty.network.http.httpenum.HttpMethodEnum;
import com.haochang.chunkvod.tools.thirdparty.network.http.httpenum.HttpRequestLoadingEnum;
import com.haochang.chunkvod.tools.thirdparty.network.http.request.HttpRequestBuilder;
import com.haochang.chunkvod.tools.thirdparty.network.http.request.HttpRequestTask;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

/**
 * 点餐首页房间服务状态监听
 *@author qintao
 *created at 2016/12/12 17:10
 */

public class RoomStatusService extends Service
{

	private Timer timer;
	private TimerTask timerTask;

	@Override
	public void onCreate()
	{
		super.onCreate();
		initTimer();
	}

	@Override
	public IBinder onBind(Intent intent)
	{
		return null;
	}

	/**
	 * 全局timer，用于每半小时检查一次购物车，不满足条件的就清空购物车
	 */
	private void initTimer()
	{
		timer = new Timer();
		timerTask = new TimerTask()
		{
			@Override
			public void run()
			{
				handler.sendEmptyMessage(0);
			}
		};
		timer.schedule(timerTask, 5000, 10000);
	}

	Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			// TODO: 2016/12/12 请求接口之前判断下是否登录UserToken.isTokenExist(),存在token则请求//请求接口最好重新写一个
			//弊端:当停留在房间首页时候，屏幕震动可能与房间的闪烁效果不同步
			//修改：如果当前页面处在OrderHomePageActivity则不请求接口 2016/142/19
			if (UserToken.isTokenExist() && !ActivityTaskUtil.getInstance().isTopActivity(RoomStatusService.this, OrderHomePageActivity.class.getName()))
				requestIsServiceCome();
		}
	};

	/**
	 * 判断是否有服务来临
	 */
	private void requestIsServiceCome()
	{
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("area_ids", "");
		map.put("sort_type", "room");
		HttpRequestTask httpRequestTask = new HttpRequestBuilder(BaseApplication.appContext).interfaceName(ApiConfig.ORDER_ROOM_STATUS).param(map)
				.httpMethodEnum(HttpMethodEnum.GET).localCache(HttpCacheEnum.ENABLE_VALID).httpRequestLoadingEnum(HttpRequestLoadingEnum.HTTP_LOADING_NONE)
				.httpRequestSucessListener(new HttpRequestBuilder.IHttpRequestSucessListener()
				{

					@Override
					public void onResponseSucess(JSONObject jsonObject)
					{
						if (jsonObject != null)
						{
							List<RoomInfo> list = parseRoomJson(jsonObject);
							if (!CollectionUtils.isEmpty(list))
							{
								if (isOpenVibrator(list))
								{
									KeyguardManagerUtil.getInstance().keyguardAndAcquire(RoomStatusService.this);
									VibratorUtil.getInstance().startVibrate(RoomStatusService.this, true);
								} else
									VibratorUtil.getInstance().stopVibrate();
							} else
								VibratorUtil.getInstance().stopVibrate();
						} else
							VibratorUtil.getInstance().stopVibrate();
					}
				}).build();
		httpRequestTask.execute();
	}

	/**
	 * 解析包房
	 *
	 * @param jsonObject jsonObject
	 * @return 房间列表
	 */
	private List<RoomInfo> parseRoomJson(JSONObject jsonObject)
	{
		ArrayList<RoomInfo> roomInfoList = new ArrayList<RoomInfo>();
		JSONArray jsonArray = jsonObject.optJSONArray("list");
		if (jsonArray != null && jsonArray.length() > 0)
		{
			for (int i = 0; i < jsonArray.length(); i++)
			{
				JSONObject jObject = jsonArray.optJSONObject(i);
				if (jObject == null)
					continue;
				RoomInfo info = new RoomInfo();
				info.setFlick(1 == jObject.optInt("is_on_service"));
				info.setRoomId(jObject.optString("room_id"));
				roomInfoList.add(info);
			}
		}
		return roomInfoList;
	}

	/**
	 * 是否开启震动服务的判断
	 */
	private boolean isOpenVibrator(List<RoomInfo> list)
	{
		if (CollectionUtils.isEmpty(list))
			return false;
		boolean flag = false;
		for (int i = 0; i < list.size(); i++)
		{
			RoomInfo roomInfo = list.get(i);
			if (roomInfo.isFlick())
			{
				flag = true;
				break;
			}
		}
		return flag;
	}

	@Override
	public void onDestroy()
	{
		cancelTask();
		super.onDestroy();
	}

	private void cancelTask()
	{
		if (timer != null)
		{
			timer.cancel();
			timer = null;
		}
		if (timerTask != null)
		{
			timerTask.cancel();
			timerTask = null;
		}
	}
}
